package top.gbiot.scan.service;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import org.apache.commons.net.util.SubnetUtils;


@Service
public class IoScanAiService {
    private static final int TIMEOUT = 300;

    private static final Pattern CIDR_PATTERN = Pattern.compile("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/([0-9]|[1-2][0-9]|3[0-2])$");

    // 检查CIDR格式是否有效
    public  boolean isValidCIDR(String cidr) {
        if (cidr == null) {
            return false;
        }
        Matcher matcher = CIDR_PATTERN.matcher(cidr);
        return matcher.matches();
    }

    public List<String> scanActiveDevices(String cidr) {
        List<String> activeIps = new ArrayList<>();
        SubnetUtils utils = new SubnetUtils(cidr);
        String[] allIps = utils.getInfo().getAllAddresses();

        ExecutorService executor = Executors.newFixedThreadPool(20);
        for (String ip : allIps) {
            executor.execute(() -> {
                if (ping(ip)) activeIps.add(ip);
            });
        }
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return activeIps;
    }

    private boolean ping(String ip) {
        System.out.println("ping "+ ip);
        try {
            return InetAddress.getByName(ip).isReachable(TIMEOUT);
        } catch (IOException e) {
            return false;
        }
    }
}
